package org.esgl3d.rendering;

import java.nio.IntBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.Bitmap;
import android.opengl.GLUtils;

public class TextureManager {
	private GL10 gl;
	
	public void setGl(GL10 value) {
		gl = value;
	}
	
	public Texture addImage(Bitmap bitmap, boolean mipmaps) {
		
		IntBuffer texturesBuffer = IntBuffer.allocate(1);
		
		gl.glEnable(GL10.GL_TEXTURE_2D);
		gl.glGenTextures(1, texturesBuffer);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, texturesBuffer.get(0));

		int textuteMode = GL10.GL_LINEAR;
		// setup texture parameters
		if (mipmaps)
			textuteMode = GL10.GL_LINEAR_MIPMAP_LINEAR;
			
		gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
				textuteMode);
		gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
				textuteMode);
		
		gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
				GL10.GL_CLAMP_TO_EDGE);
		gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
				GL10.GL_CLAMP_TO_EDGE);
		
		if (mipmaps)
			buildMipmap(gl, bitmap, 32);
		else
			buildMipmap(gl, bitmap, 1);
		
		Texture result = new Texture(texturesBuffer.get(0), bitmap.getWidth(), bitmap.getHeight());
		
		return result;
	}
	
	void buildMipmap(GL10 gl, Bitmap bitmap, int count) {
		//
		int level = 0;
		//
		int height = bitmap.getHeight();
		int width = bitmap.getWidth();
		
		

		while ( (height >= 1 || width >= 1) && (count > 0) ) {
			// First of all, generate the texture from our bitmap and set it to
			// the according level
			GLUtils.texImage2D(GL10.GL_TEXTURE_2D, level, bitmap, 0);

			//
			if (height == 1 || width == 1) {
				break;
			}

			// Increase the mipmap level
			level++;

			//
			height /= 2;
			width /= 2;
			Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap, width, height,
					true);

			// Clean up
			bitmap.recycle();
			bitmap = bitmap2;
			count--;
		}
	}
}
